package cloud.simple.service.k8s.probe;

import cloud.simple.service.k8s.probe.hook.IK8sCheckReadinessHook;
import cloud.simple.service.k8s.probe.hook.IK8sCheckStartupHook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class K8sProbeChecker implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    static final int SC_OK = 200;
    static final int SC_SERVICE_UNAVAILABLE = 503;

    public int startup() {
        Map<String, IK8sCheckStartupHook> hooks = this.applicationContext.getBeansOfType(IK8sCheckStartupHook.class);
        log.info("K8sProbeChecker-startup: {} k8s check startup hook searched", hooks.size());

        for (Map.Entry<String, IK8sCheckStartupHook> hookEntry : hooks.entrySet()) {
            IK8sCheckStartupHook kook = hookEntry.getValue();
            try {

                log.info("K8sProbeChecker-startup: {} start checking", hookEntry.getKey());
                kook.check();
                log.info("K8sProbeChecker-startup: {} checked", hookEntry.getKey());

            } catch (Exception e) {
                log.error("K8sProbeChecker-startup: {} check failed", hookEntry.getKey(), e);
                return SC_SERVICE_UNAVAILABLE;
            }
        }

        return SC_OK;
    }

    public int readiness() {
        Map<String, IK8sCheckReadinessHook> hooks = this.applicationContext.getBeansOfType(IK8sCheckReadinessHook.class);
        log.info("K8sProbeChecker-readiness: {} k8s check readiness hook searched", hooks.size());

        for (Map.Entry<String, IK8sCheckReadinessHook> hookEntry : hooks.entrySet()) {
            IK8sCheckReadinessHook kook = hookEntry.getValue();
            try {

                log.info("K8sProbeChecker-readiness: {} start checking", hookEntry.getKey());
                kook.check();
                log.info("K8sProbeChecker-readiness: {} checked", hookEntry.getKey());

            } catch (Exception e) {
                log.error("K8sProbeChecker-readiness: {} check failed", hookEntry.getKey(), e);
                return SC_SERVICE_UNAVAILABLE;
            }
        }

        return SC_OK;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
